﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using AIMLbot;
using ChatBuddy.Classes.Helpers.Friend_Helper;
using ChatBuddy.Classes.Helpers.Guild_Helper;
using ChatBuddy.Classes.Objects;
using ChatBuddy.Forms.Secondary.EmailWindow;
using CustomUIControls;
using IniParser;
using IniParser.Model;
using Styx.WoWInternals.Misc;


namespace ChatBuddy.Forms.Primary.SettingsWindow
{
    public partial class SettingsWindow : Form
    {

        private Bot _bot;
        private User _user;
        private bool _busy = false;
        public static Queue<IncomingMessage> answerQueue = new Queue<IncomingMessage>();
        private List<string> DefaultMesg = new List<string>();
        private readonly Random _rand = new Random(DateTime.Now.Millisecond);
        private FileIniDataParser dataParser = new FileIniDataParser();
        private IniData iniParsed = new IniData();

        public SettingsWindow()
        {
            InitializeComponent();
        }

        private void SettingsWindow_Load(object sender, EventArgs e)
        {
            try
            {
                // load the version information
                lblVersioning.Text = lblVersioning.Text.Replace("[VERSION]", Application.ProductVersion);

                // load the images
                ilTab.Images.Add(Image.FromFile(Path.Combine(Application.StartupPath, @"plugins\ChatBuddy\bin\img\icon_home.png")));
                ilTab.Images.Add(Image.FromFile(Path.Combine(Application.StartupPath, @"plugins\ChatBuddy\bin\img\icon_settings.png")));
                ilTab.Images.Add(Image.FromFile(Path.Combine(Application.StartupPath, @"plugins\ChatBuddy\bin\img\icon_console.png")));

                btnClear.Image = Image.FromFile(Path.Combine(Application.StartupPath, @"plugins\ChatBuddy\bin\img\icon_clean.png"));
                btnLvLogClear.Image = Image.FromFile(Path.Combine(Application.StartupPath, @"plugins\ChatBuddy\bin\img\icon_brush.png"));
                btnLvLogExport.Image = Image.FromFile(Path.Combine(Application.StartupPath, @"plugins\ChatBuddy\bin\img\icon_export.png"));
                pbLogo.Image = Image.FromFile(Path.Combine(Application.StartupPath, @"plugins\ChatBuddy\bin\img\logo.png"));

                Icon = new Icon(Path.Combine(Application.StartupPath, @"plugins\ChatBuddy\bin\img\icon.ico"));

                // create a generic bot
                _bot = new Bot();
                _bot.loadSettings();
                _bot.loadAIMLFromFiles();
                _user = new User("bot", _bot);

                // verify user has settings
                VerifySettings();
            }
            catch (Exception er)
            {
                MessageBox.Show(er.ToString());
            }
        }

        private void VerifySettings()
        {
            if (!File.Exists(Path.Combine(Application.StartupPath, @"plugins\ChatBuddy\bin\Settings\chatbuddy.ini")))
            {
                dataParser = new FileIniDataParser();
                iniParsed = new IniData();

                // general section
                iniParsed.Sections.AddSection("General");
                iniParsed.Sections.GetSectionData("General").Keys.AddKey("AutomaticUpdates", "True");
                iniParsed.Sections.GetSectionData("General").Keys.AddKey("Balloons", "True");
                iniParsed.Sections.GetSectionData("General").Keys.AddKey("Email", "False");
                iniParsed.Sections.GetSectionData("General").Keys.AddKey("WSVC", "False");

                // audio section
                iniParsed.Sections.AddSection("Audio");
                iniParsed.Sections.GetSectionData("Audio").Keys.AddKey("whisper", "True");
                iniParsed.Sections.GetSectionData("Audio").Keys.AddKey("name", "True");
                iniParsed.Sections.GetSectionData("Audio").Keys.AddKey("gm", "True");

                // response section
                iniParsed.Sections.AddSection("Response");
                iniParsed.Sections.GetSectionData("Response").Keys.AddKey("friends", "False");
                iniParsed.Sections.GetSectionData("Response").Keys.AddKey("guild", "False");
                iniParsed.Sections.GetSectionData("Response").Keys.AddKey("whispers", "False");

                // message handling section
                iniParsed.Sections.AddSection("MHandle");
                iniParsed.Sections.GetSectionData("MHandle").Keys.AddKey("Ignore", "2");
                iniParsed.Sections.GetSectionData("MHandle").Keys.AddKey("Hard", "False");
                iniParsed.Sections.GetSectionData("MHandle").Keys.AddKey("Notification", "False");

                // gm handling
                iniParsed.Sections.AddSection("GM");
                iniParsed.Sections.GetSectionData("GM").Keys.AddKey("Respond", "False");
                iniParsed.Sections.GetSectionData("GM").Keys.AddKey("Hearth", "False");

                // email settings
                iniParsed.Sections.AddSection("Email");
                iniParsed.Sections.GetSectionData("Email").Keys.AddKey("Host", "smtp.gmail.com");
                iniParsed.Sections.GetSectionData("Email").Keys.AddKey("Port", "995");
                iniParsed.Sections.GetSectionData("Email").Keys.AddKey("User", "myemail@gmail.com");
                iniParsed.Sections.GetSectionData("Email").Keys.AddKey("Password", "randompassword");
                iniParsed.Sections.GetSectionData("Email").Keys.AddKey("SSL", "False");
                iniParsed.Sections.GetSectionData("Email").Keys.AddKey("Type", "1");
                iniParsed.Sections.GetSectionData("Email").Keys.AddKey("UseNotification", "False");
                iniParsed.Sections.GetSectionData("Email").Keys.AddKey("Interval", "22");
 

                dataParser.SaveFile(Path.Combine(Application.StartupPath, @"plugins\ChatBuddy\bin\Settings\chatbuddy.ini"), iniParsed);

                VerifySettings();
            }
            else
            {
                dataParser = new FileIniDataParser();
                var parser = dataParser.ReadFile(Path.Combine(Application.StartupPath, @"plugins\ChatBuddy\bin\Settings\chatbuddy.ini"));

                ckBoxShowBalloon.Checked = Convert.ToBoolean(parser["General"]["Balloons"]);
                ckBoxEmail.Checked = Convert.ToBoolean(parser["General"]["Email"]);
                ckBoxWebService.Checked = Convert.ToBoolean(parser["General"]["WSVC"]);
                ckBoxNotifyOnWhisper.Checked = Convert.ToBoolean(parser["Audio"]["whisper"]);
                ckBoxNotifyOnName.Checked = Convert.ToBoolean(parser["Audio"]["name"]);
                ckBoxNotifyOnGm.Checked = Convert.ToBoolean(parser["Audio"]["gm"]);
                ckBoxRespondFriends.Checked = Convert.ToBoolean(parser["Response"]["friends"]);
                ckBoxRespondGuild.Checked = Convert.ToBoolean(parser["Response"]["guild"]);
                ckBoxRespondGm.Checked = Convert.ToBoolean(parser["GM"]["Respond"]);
                ckBoxHearth.Checked = Convert.ToBoolean(parser["GM"]["Hearth"]);
                nudIgnore.Value = Convert.ToDecimal(parser["MHandle"]["Ignore"]);
                ckBoxHardIgnore.Checked = Convert.ToBoolean(parser["MHandle"]["Hard"]);
                ckBoxSendNotification.Checked = Convert.ToBoolean(parser["MHandle"]["Notification"]);
            }
        }

        private void SaveSettings()
        {
            dataParser = new FileIniDataParser();
            var parser = dataParser.ReadFile(Path.Combine(Application.StartupPath, @"plugins\ChatBuddy\bin\Settings\chatbuddy.ini"));

            parser["General"]["Balloons"] = ckBoxShowBalloon.Checked.ToString();
            parser["General"]["Email"] = ckBoxEmail.Checked.ToString();
            parser["General"]["WSVC"] = ckBoxWebService.Checked.ToString();
            parser["Audio"]["whisper"] = ckBoxNotifyOnWhisper.Checked.ToString();
            parser["Audio"]["name"] = ckBoxNotifyOnName.Checked.ToString();
            parser["Audio"]["gm"] = ckBoxNotifyOnGm.Checked.ToString();
            parser["Response"]["friends"] = ckBoxRespondFriends.Checked.ToString();
            parser["Response"]["guild"] = ckBoxRespondGuild.Checked.ToString();
            parser["Response"]["whispers"] = ckBoxRespondWhispers.Checked.ToString();
            parser["GM"]["Respond"] = ckBoxRespondGm.Checked.ToString();
            parser["GM"]["Hearth"] = ckBoxHearth.Checked.ToString();
            parser["MHandle"]["Ignore"] = Convert.ToString(nudIgnore.Value);
            parser["MHandle"]["Hard"] = ckBoxHardIgnore.Checked.ToString();
            parser["MHandle"]["Notification"] = ckBoxSendNotification.Checked.ToString();

            dataParser.SaveFile(Path.Combine(Application.StartupPath, @"plugins\ChatBuddy\bin\Settings\chatbuddy.ini"), parser);
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            var msg = new IncomingMessage(tbTestQuery.Text, "Unknown", "", "");
            //answerQueue.Enqueue(msg);
            HandleMessage(msg);
        }

        private void HandleMessage(IncomingMessage m)
        {
            var r = new Request(m.msg, _user, _bot);
            var returnString = _bot.Chat(r).Output;

            rtbQuery.SelectionStart = rtbQuery.TextLength;
            rtbQuery.SelectionLength = 0;
            rtbQuery.SelectionColor = Color.Blue;

            rtbQuery.AppendText("Me: " + m.msg + Environment.NewLine);

            rtbQuery.SelectionStart = rtbQuery.TextLength;
            rtbQuery.SelectionLength = 0;
            rtbQuery.SelectionColor = Color.Red;

            rtbQuery.AppendText("Bot: " + returnString + Environment.NewLine);
            rtbQuery.ScrollToCaret();

            tbTestQuery.Text = null;
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnQuery_Click(null, null);
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            rtbQuery.Clear();
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            SaveSettings();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            UpdateGuildListing();
        }

        private void UpdateGuildListing()
        {
            /*
            var guildWorker = new BackgroundWorker();
            guildWorker.DoWork += guildWorker_DoWork;
            guildWorker.RunWorkerCompleted +=guildWorker_RunWorkerCompleted;
            guildWorker.RunWorkerAsync();
             */
            var list = new FriendLister().GetBnetFriends();

            foreach (var friendMember in list)
            {
                MessageBox.Show(friendMember.Name);
            }
        }

        private void ResetStatus()
        {
            tStripStatus.Text = "Idle";
        }

        private void guildWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ResetStatus();
        }

        private void guildWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            tStripStatus.Text = "Fetching guild listings.";
            var list = new GuildLister().GetGuildies();

            foreach (var guildMember in list)
            {
                tStripStatus.Text = String.Format("[{0}] [{1}]", guildMember.User, guildMember.Id);
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            new EmailWindow().ShowDialog();
        }
    }
}
